package cn.fanyamin.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fanyamin.model.Book;
import cn.fanyamin.model.Category;

public class BookNoDbDao implements BookDao {
    private static Map<Integer, Category> categoriesMap;
    private static List<Book> books;

    static {
        books = new ArrayList<Book>();
        books.add(new Book(new Integer(1), "20110731", "Thinking in C++", "C++", new Date()));
        books.add(new Book(new Integer(2), "20110731", "Thinking in Java", "Java", new Date()));
        CategoryDao categoryDao = new CategoryNoDbDao();
        categoriesMap = categoryDao.getCategoriesMap();
    }

    private static Log logger = LogFactory.getLog(BookNoDbDao.class);

    public List<Book> getAllBooks() {
        return books;
    }

    public Book getBook(Integer id) {
        Book emp = null;
        Iterator<Book> iter = books.iterator();
        while (iter.hasNext()) {
            emp = (Book)iter.next();
            if (emp.getBookId().equals(id)) {
                break;
            }
        }
        return emp;
    }

    public void update(Book book) {
        Integer id = book.getBookId();
        for (int i = 0; i < books.size(); i++) {
            Book tempBook = (Book)books.get(i);
            if (tempBook.getBookId().equals(id)) {
                book.setCategory((Category)categoriesMap.get(book.getCategory().getCategoryId()));
                books.set(i, book);
                break;
            }
        }
    }

    public void insert(Book aBook) {
        int lastId = 0;
        Iterator<Book> iter = books.iterator();
        while (iter.hasNext()) {
            Book temp = (Book)iter.next();
            if (temp.getBookId().intValue() > lastId) {
                lastId = temp.getBookId().intValue();
            }
        }
        Category cg = aBook.getCategory();
        if(null != cg) {
            aBook.setCategory((Category)categoriesMap.get(cg.getCategoryId()));
        }
        aBook.setBookId(new Integer(lastId + 1));
        books.add(aBook);
    }

    public void delete(Integer id) {
        for (int i = 0; i < books.size(); i++) {
            Book tempBook = (Book)books.get(i);
            if (tempBook.getBookId().equals(id)) {
                books.remove(i);
                break;
            }
        }
    }}
